<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/23
 * Time: 13:01
 */

namespace App\Game\Traits;

use Carbon\Carbon;

trait IgTrait
{
    public function igrequest($action, $url, $data)
    {
        $json['hashCode'] = $this->hashCode;
        $json['command'] = $action;
        $json['params'] = $data;
//        file_put_contents('/home/gameapi/storage/logs/test.log', '2222...'.json_encode($json).PHP_EOL, FILE_APPEND);
        $json = json_encode($json);
        $output = $this->post_data($url,$json,$this->header);
//        file_put_contents('/home/gameapi/storage/logs/test.log', '1111111...'.$output.PHP_EOL, FILE_APPEND);
        $output = json_decode($output, true);
        return $output;
    }

    private function post_data($url,$data,$headers = null)
    {
        $ch = curl_init();
        if(substr($url,0,5)=='https'){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($headers){
            $header= [];
            foreach ($headers as $k => $v){
                $header[] = $k.':'.$v;
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $response = curl_exec($ch);
        if($error=curl_error($ch)){
            file_put_contents('/home/gameapi/storage/logs/test.log', 'ig..post_error...'.$error.PHP_EOL, FILE_APPEND);
            return $error;
        }
        curl_close($ch);
        //var_dump($response);
        return $response;
    }
}